package com.situ.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.situ.entity.Product;
import com.situ.entity.User;
import com.situ.service.UserService;
import com.situ.service.impl.UserServiceImpl;
import com.situ.vo.ResultVO;
import com.situ.vo.TableVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @author yangkx
 * @create 2023-08-29-10:00
 */
@WebServlet("/user")
public class UserController extends BaseController{

    UserService service = new UserServiceImpl();

    //打开页面
    public void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/WEB-INF/ControllerPage/user.jsp").forward(req,resp);
    }

    //查询表格数据
    public TableVO select(Integer page,Integer limit,String username,String phoneNumber) {
        return service.list(page,limit,username,phoneNumber);
    }

    //保存
    public ResultVO save(User u){
        return service.save(u);
    }

    //删除
    public ResultVO delete(Integer id){
        return service.delete(id);
    }

    //编辑——根据ID查询该行数据带到前台
    public void selectById(Integer id,HttpServletResponse response) throws IOException {
        User u = service.selectById(id);

        //避免乱码
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        //把User对象转换成json格式字符串
        String s = new ObjectMapper().writeValueAsString(u);
        //往前台写
        response.getWriter().write(s);
    }


}
